const weakMap = new WeakMap()
const creteLoading = (el: HTMLElement, id: string) => {
    // 使用h函数创建一个文本节点
    const text = document.createTextNode('loading...')
    // 创建一个div元素
    const div = document.createElement('div')
    const { height, width, top, left } = el.getBoundingClientRect()
    // 设置div的样式
    div.id = id
    div.style.position = 'absolute'
    div.style.top = `${top}px`
    div.style.left = `${left}px`
    div.style.width = `${width}px`
    div.style.height = `${height}px`
    div.style.zIndex = '10'
    div.style.backgroundColor = 'rgba(0, 0, 0, 0.4)'
    div.style.color = '#fff'
    div.style.fontSize = '14px'
    div.style.display = 'flex'
    div.style.justifyContent = 'center'
    div.style.alignItems = 'center'
    // 将文本节点添加到div中
    div.appendChild(text)
    return div
}
const clear = (id: string) => {
    const div = document.getElementById(`${id}`)

    if (div) {
        div.remove()
    }
}
const createId = () => (Math.floor(Math.random() * 10000000).toString(16))
export default {
    mounted(el: HTMLElement, bind: any) {
        if (bind.value) {
            // 将div添加到el中
            const id = createId()
            el.appendChild(creteLoading(el, id))
            weakMap.set(el, id)
        }
    },
    updated(el: HTMLElement, bind: any) {
        if (bind.value) {
            const id = createId()
            el.appendChild(creteLoading(el, id))
            weakMap.set(el, id)
        } else {
            const id = weakMap.get(el)
            clear(id)
            weakMap.delete(el)
        }
    },
    unmounted(el: HTMLElement) {
        const id = weakMap.get(el)
        if (id) {
            clear(id)
            weakMap.delete(el)
        }
    }
}